<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <custom-navbar title="开始充电" backgroundColor="#42a5f5" titleColor="#ffffff"></custom-navbar>

    <!-- 刷新加载框 -->
    <view class="refresh-loading" v-if="isRefreshing">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在刷新...</text>
    </view>

    <!-- 充电站信息卡片 -->
    <view class="station-card" style="margin-top: 100px;">
      <view class="card-title">充电站信息</view>
      <view class="station-details">
        <view class="info-item">
          <text class="item-label">充电桩编号：</text>
          <text class="item-value">{{ pileId || 'GZ-2023-1265' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">站点名称：</text>
          <text class="item-value">{{ chargingStation.name }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">设备功率：</text>
          <text class="item-value">{{ chargingStation.power }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">设备状态：</text>
          <text class="item-value">{{ chargingStation.status }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">电费单价：</text>
          <text class="item-value">{{ chargingStation.price }}</text>
        </view>
      </view>
    </view>

    <!-- 充电模式 -->
    <view class="charge-section">
      <view class="section-title">充电模式</view>
      <view class="charge-mode-card active">
        <text>快速充电</text>
      </view>
    </view>

    <!-- 预估费用信息 -->
    <view class="cost-section">
      <view class="cost-item">
        <text class="item-label">预估费用：</text>
        <text class="item-value price">{{ estimatedCost }}</text>
      </view>
      <view class="cost-item">
        <text class="item-label">预计充电时间：</text>
        <text class="item-value">{{ estimatedTime }}</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="start-btn" @tap="startCharging" :class="{ 'disabled': isRequesting }">{{ isRequesting ? '正在启动...' :
      '开始充电' }}</view>

    <!-- 启动充电等待弹框 -->
    <view class="charging-overlay" v-if="showRequestTime">
      <view class="charging-modal">
        <view class="modal-header">
          <text>正在启动充电</text>
        </view>
        <view class="modal-content">
          <view class="progress-circle-container">
            <view class="progress-circle">
              <view class="circle-bg"></view>
              <!-- 注释蓝色加载条
              <view class="progress" :style="{ transform: `rotate(${progressDegrees}deg)` }"></view>
              <view class="mask" v-if="requestSeconds / requestTimeout > 0.5"></view>
              -->
              <view class="inner-circle">
                <text class="countdown">{{ requestTimeout - requestSeconds }}</text>
                <text class="countdown-label">秒</text>
              </view>
            </view>
          </view>
          <view class="status-message">
            <text>充电桩启动中，请稍候...</text>
          </view>
          <view class="progress-steps">
            <view class="step" :class="{ active: requestSeconds >= 5 }">
              <view class="step-dot"></view>
              <text>设备连接</text>
            </view>
            <view class="step" :class="{ active: requestSeconds >= 15 }">
              <view class="step-dot"></view>
              <text>身份验证</text>
            </view>
            <view class="step" :class="{ active: requestSeconds >= 30 }">
              <view class="step-dot"></view>
              <text>充电准备</text>
            </view>
            <view class="step" :class="{ active: requestSeconds >= 45 }">
              <view class="step-dot"></view>
              <text>电路检测</text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <!-- <text>若长时间无响应，可取消后重试</text>
          <view class="cancel-btn" @tap="cancelCharging">取消充电</view> -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import startChargingApi from '@/src/api/startCharging'
import CustomNavbar from '@/components/CustomNavbar.vue'

export default {
  // 页面配置，启用下拉刷新
  onPullDownRefresh() {
    console.log("下拉刷新，重新查询插枪状态");
    // 获取充电桩ID
    const pileId = this.pileId || this.$store.state.charger.pileId;
    if (pileId) {
      // 显示刷新状态
      this.isRefreshing = true;
      // 重新查询插枪状态
      this.checkPlugStatus(pileId, true);
    } else {
      uni.showToast({
        title: '充电桩ID不存在，请重新扫码',
        icon: 'none'
      });
      // 停止下拉刷新动画
      uni.stopPullDownRefresh();
    }
  },
  
  components: {
    CustomNavbar
  },

  // 禁止页面滚动
  disableScroll: true,

  data() {
    return {
      pileId: '',
      socketSn: '',
      // 充电枪状态
      isPlugged: null,
      chargingStation: {
        name: '科技园充电站',
        power: '180kW',
        status: '可用',
        price: '¥1.8/度（峰时）'
      },
      estimatedCost: '¥90.00',
      estimatedTime: '约40分钟',
      requestTimer: null, // 请求计时器
      requestSeconds: 0, // 请求已经过的秒数
      showRequestTime: false, // 是否显示请求时间
      requestTimeout: 60, // 请求超时时间，默认60秒
      isRequesting: false, // 是否正在请求中
      isRefreshing: false // 是否正在刷新中
    }
  },

  onLoad(options) {
    console.log("执行onLoad生命周期函数");
    // 从页面参数或store中获取充电桩ID
    this.pileId = options.pileId || this.$store.state.charger.pileId;
    console.log('充电桩ID:', this.pileId);

    // 自动查询插枪状态，显示加载中状态
    uni.showLoading({
      title: '正在查询插枪状态...',
      mask: true
    });
    this.checkPlugStatus(this.pileId);
  },

  onShow() {
    console.log("执行onShow生命周期函数");
    // onShow中不重复执行初始化逻辑，避免重复请求
  },
  methods: {
    // 检测充电枪是否插入
    checkPlugStatus(pileId, isPullDownRefresh = false) {
      // 检查pileId是否存在
      if (!pileId) {
        if (!isPullDownRefresh) {
          uni.hideLoading();
        } else {
          this.isRefreshing = false;
          uni.stopPullDownRefresh();
        }
        
        uni.showToast({
          title: '充电桩ID不存在，请重新扫码',
          icon: 'none',
          duration: 2000
        });

        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
        return;
      }

      // 根据刷新方式设置状态
      if (isPullDownRefresh) {
        // 下拉刷新时设置刷新状态
        this.isRefreshing = true;
      } else {
        // 非下拉刷新时显示loading
        uni.showLoading({
          title: '正在查询插枪状态...',
          mask: true
        });
      }

      // 已显示loading状态，这里不需要重复显示
      startChargingApi.getChargingProgress(pileId).then(res => {
        if (!isPullDownRefresh) {
          uni.hideLoading();
        } else {
          // 如果是下拉刷新，停止下拉刷新动画并清除状态
          this.isRefreshing = false;
          uni.stopPullDownRefresh();
        }
        
        console.log('充电枪状态:', res.data.insertState);
        this.socketSn = res.data.socketSn;

        if (res.data.insertState === 0) {
          this.isPlugged = true;
          uni.showToast({
            title: '充电枪已连接',
            icon: 'success',
            duration: 1500
          });
        } else {
          this.isPlugged = false;
          uni.showToast({
            title: '未检测到充电枪连接',
            icon: 'none',
            duration: 1500
          });

          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/replug/replug'
            });
          }, 1500);
        }
      }).catch(err => {
        if (!isPullDownRefresh) {
          uni.hideLoading();
        } else {
          // 如果是下拉刷新，停止下拉刷新动画并清除状态
          this.isRefreshing = false;
          uni.stopPullDownRefresh();
        }
        
        console.error('检测充电枪状态失败:', err);

        uni.showToast({
          title: '检测充电枪状态失败，请重试',
          icon: 'none',
          duration: 2000
        });
      });
    },
    startCharging() {
      // 如果已经在请求中，则不重复发送
      if (this.isRequesting) return;

      // 检查充电枪连接状态
      if (!this.isPlugged) {
        uni.showToast({
          title: '充电枪未连接，请先连接充电枪',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 设置请求状态
      this.isRequesting = true;
      this.showRequestTime = true;
      this.requestSeconds = 0;

      // 启动定时器，每秒更新一次请求时间
      this.requestTimer = setInterval(() => {
        this.requestSeconds++;

        // 检查是否超时
        if (this.requestSeconds >= this.requestTimeout) {
          this.handleRequestTimeout();
        }
      }, 1000);
      // 调用真实API启动充电
      startChargingApi.startCharging(
        this.pileId,
        this.socketSn
      ).then(res => {
        console.log('启动充电响应:', res);

        // 如果已经超时处理过了，则不再处理成功响应
        if (!this.isRequesting) return;

        // 清除定时器和状态
        this.clearRequestTimer();

        // 直接处理原始响应对象
        if (res && (res.startState === 0 || res.code === 200)) {
          // 保存充电枪编号到全局状态
          this.$store.dispatch('charger/setSocketSn', this.socketSn);
          // 处理成功响应
          this.handleRequestSuccess();
        } else {
          // 处理失败响应
          const errorMsg = res && res.msg ? res.msg : '启动充电失败，请重试';
          this.handleRequestFailure(errorMsg);
        }
      }).catch(err => {
        console.error('启动充电失败:', err);

        // 如果已经超时处理过了，则不再处理失败响应
        if (!this.isRequesting) return;

        // 清除定时器和状态
        this.clearRequestTimer();

        // 处理请求错误
        this.handleRequestFailure('网络请求失败，请检查网络后重试');
      });
    },

    // 清除请求定时器
    clearRequestTimer() {
      if (this.requestTimer) {
        clearInterval(this.requestTimer);
        this.requestTimer = null;
      }
      this.isRequesting = false;
      this.showRequestTime = false;
      uni.hideLoading();
    },

    // 处理请求超时
    handleRequestTimeout() {
      this.clearRequestTimer();
      uni.showModal({
        title: '提示',
        content: '启动充电请求超时，请稍后重试',
        showCancel: false
      });
    },

    // 处理请求成功
    handleRequestSuccess() {
      uni.showToast({
        title: '启动充电成功',
        icon: 'success',
      });

      // 成功后延迟跳转到充电中页面
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/chargingProgress/chargingProgress'
        });
      }, 100);
    },

    // 处理请求失败
    handleRequestFailure(message) {
      uni.showModal({
        title: '提示',
        content: message || '启动充电失败，请稍后重试',
        showCancel: false
      });
    },

    goToReplugPage() {
      uni.redirectTo({
        url: '/pages/replug/replug'
      });
    },
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding: 16px;
  padding-bottom: 120px; /* Add more padding at the bottom to prevent TabBar overlap */
}

.header-btn {
  background-color: #1989fa;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  text-align: center;
  padding: 30rpx 0;
  margin-bottom: 30rpx;
}

.pile-info {
  margin-bottom: 16px;

  .pile-id {
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }
}

.station-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 24px; /* Increased spacing */

  .card-title {
    font-size: 16px;
    font-weight: 500;
    text-align: center;
    padding: 14px 0; /* Increased padding */
    background-color: #42a5f5;
    color: #fff;
  }

  .station-details {
    padding: 20px;

    .info-item {
      display: flex;
      margin-bottom: 16px; /* Increased spacing between items */

      &:last-child {
        margin-bottom: 0;
      }

      .item-label {
        color: #333;
        min-width: 90px;
        font-weight: 500; /* Added for better readability */
      }

      .item-value {
        flex: 1;
        color: #666;
      }
    }
  }
}

.charge-section {
  margin-bottom: 20px;

  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 16px;
    padding-left: 4px;
    font-weight: 500;
  }

  .charge-mode-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 18px; /* Increased padding */
    text-align: center;
    font-size: 16px;
    color: #333;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    &.active {
      background-color: #f0f9ff;
      border-left: 4px solid #42a5f5;
      color: #42a5f5;
      font-weight: 500;
    }
  }
}

.cost-section {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .item-label {
      color: #333;
    }

    .item-value {
      font-weight: 500;

      &.price {
        color: #ff6b00;
        font-weight: bold;
        font-size: 18px;
      }
    }
  }
}

.start-btn {
  margin-top: auto;
  margin-bottom: 100px; /* Increased in previous edit */
  height: 50px; /* Increased height for better visibility */
  line-height: 50px;
  text-align: center;
  background-color: #ff6b00;
  color: #fff;
  font-size: 18px; /* Increased font size */
  font-weight: 500; /* Added font weight */
  border-radius: 45px;
  box-shadow: 0 4rpx 10rpx rgba(255, 106, 60, 0.3);

  &:active {
    transform: scale(0.98); /* Added scale effect on press */
    background-color: #e86000;
  }

  &.disabled {
    opacity: 0.7;
    background-color: #ccc;
    box-shadow: none;
  }
}

.test-btn {
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #999999;
  color: #fff;
  font-size: 14px;
  border-radius: 40px;
  margin-bottom: 16px;
}

/* 充电启动弹框样式 */
.charging-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.charging-modal {
  width: 90%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 20px 0;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  background-color: #42a5f5;
  color: #fff;
}

.modal-content {
  padding: 30px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-circle-container {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20px;
}

.progress-circle {
  position: relative;
  width: 100%;
  height: 100%;
}

.circle-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 6px solid #f0f0f0;
  border-radius: 50%;
  box-sizing: border-box;
}

/* 注释蓝色加载条样式
.progress {
  position: absolute;
  top: 0;
  left: 0;
  width: 50%;
  height: 100%;
  border-radius: 100px 0 0 100px;
  background-color: transparent;
  transform-origin: right center;
  transform: rotate(0deg);
  z-index: 2;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -6px;
    left: -6px;
    width: 200%;
    height: 100%;
    border: 6px solid #42a5f5;
    border-radius: 50%;
    box-sizing: content-box;
  }
}

.mask {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  background-color: transparent;
  z-index: 3;

  &::before {
    content: '';
    position: absolute;
    top: -6px;
    left: -6px;
    width: 200%;
    height: 100%;
    border: 6px solid #42a5f5;
    border-radius: 50%;
    box-sizing: content-box;
  }
}
*/

.inner-circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70%;
  height: 70%;
  background-color: #fff;
  border-radius: 50%;
  z-index: 4;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.countdown {
  font-size: 40rpx;
  font-weight: bold;
  color: #42a5f5;
  line-height: 1;
}

.countdown-label {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.status-message {
  text-align: center;
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.progress-steps {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;

  .step-dot {
    width: 18rpx;
    height: 18rpx;
    border-radius: 50%;
    background-color: #ddd;
    margin-bottom: 8rpx;
    transition: all 0.3s;
  }

  text {
    font-size: 22rpx;
    color: #999;
    text-align: center;
    transition: all 0.3s;
  }

  &.active {
    .step-dot {
      background-color: #42a5f5;
      box-shadow: 0 0 10rpx rgba(66, 165, 245, 0.5);
    }

    text {
      color: #42a5f5;
      font-weight: 500;
    }
  }
}

.modal-footer {
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;

  text {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }

  .cancel-btn {
    padding: 8px 30px;
    background-color: #f5f5f5;
    color: #666;
    font-size: 14px;
    border-radius: 30px;

    &:active {
      opacity: 0.8;
    }
  }
}

/* 刷新加载框样式 */
.refresh-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  margin-bottom: 12px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  position: fixed;
  top: 80px;
  left: 16px;
  right: 16px;
  z-index: 100;

  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #42a5f5;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 8px;
  }

  .loading-text {
    font-size: 14px;
    color: #666;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
}
</style>
